package com.linxs.me.intefaces.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.google.gson.Gson;

/**
 * 
 * @author Linxiaosheng
 * 
 */
public class WebUtils {

	/**
	 * 
	 * @param response
	 * @throws IOException
	 */
	public static void asynchronizationResponseObject(HttpServletResponse response, Object obj) throws IOException {
		Gson gson = new Gson();
		String json = gson.toJson(obj);
		response.setContentType("application/json;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter printWriter = response.getWriter();
		printWriter.print(json);
		printWriter.flush();
		printWriter.close();
	}

	/**
	 * 
	 * @param response
	 * @throws IOException
	 */
	public static void asynchronizationResponse(HttpServletResponse response) throws IOException {
		Gson gson = new Gson();
		String json = gson.toJson(new Object());
		response.setContentType("application/json;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter printWriter = response.getWriter();
		printWriter.print(json);
		printWriter.flush();
		printWriter.close();
	}

	/**
	 * 
	 * @param <T>
	 * @param response
	 * @param list
	 * @throws IOException
	 */
	public static <T> void asynchronizationResponse(HttpServletResponse response, List<T> list) throws IOException {
		Gson gson = new Gson();
		String json = gson.toJson(list);

		response.setContentType("application/json;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");

		PrintWriter printWriter = response.getWriter();
		printWriter.print(json);
		printWriter.flush();
		printWriter.close();
	}

	/**
	 * 
	 * @param response
	 * @param message
	 * @throws IOException
	 */
	public static void asynchronizationResponse(HttpServletResponse response, String... message) {
		Gson gson = new Gson();
		List<String> list = Lists.newArrayList();
		for (String mes : message) {
			list.add(mes);
		}
		String json = gson.toJson(list);
		response.setContentType("application/json;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
		} catch (IOException e) {  
		}
		printWriter.print(json);
		printWriter.flush();
		printWriter.close();
	}

}
